/**
 * API服务模块 - 封装所有与后端API的交互
 */

interface Plan {
  plans: string[];
  intro: string[];
  user_level: number; // 添加 user_level
}

interface UserStatus {
  is_new_user: boolean;
  lang: string | null; // 可能为 null
  direction: string | null; // 可能为 null
  user_level: number | null; // 添加 user_level，可能为 null
}

interface AvailablePlan {
  lang: string;
  direction: string;
}

const API_BASE_URL = "http://localhost:5000";

/**
 * 获取用户状态
 */
export const fetchUserStatus = async (userId: string): Promise<UserStatus> => {
  const response = await fetch(`${API_BASE_URL}/api/user/status?userId=${encodeURIComponent(userId)}`);
  if (!response.ok) throw new Error(`获取用户状态失败 (${response.status})`);
  return await response.json();
};

/**
 * 获取计划列表
 */
export const fetchPlanList = async (userId: string): Promise<AvailablePlan[]> => {
  const response = await fetch(`${API_BASE_URL}/api/plans/list?userId=${encodeURIComponent(userId)}`);
  if (!response.ok) throw new Error(`查找计划列表失败 (${response.status})`);
  return await response.json();
};

/**
 * 更新用户设置
 */
export const updateUserSettings = async (
  userId: string, // 添加 userId 参数
  // level: number, // 移除 level 参数
  lang: string,
  dir: string
): Promise<void> => {
  const response = await fetch(`${API_BASE_URL}/api/user/settings`, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ userId, lang, direction: dir }), // 在请求体中包含 userId
  });

  if (!response.ok) {
    const errorData = await response.json().catch(() => ({}));
    throw new Error(`保存用户设置失败: ${errorData.error || response.statusText}`);
  }
};

/**
 * 获取计划数据
 */
export const fetchPlanData = async (userId: string): Promise<Plan> => {
  const response = await fetch(`${API_BASE_URL}/api/plan?userId=${encodeURIComponent(userId)}`);
  if (!response.ok) throw new Error(`无法获取计划数据 (${response.status})`);
  return await response.json();
};

/**
 * 生成计划
 */
export const generatePlan = async (userId: string, lang: string, direction: string): Promise<Plan> => {
  const response = await fetch(`${API_BASE_URL}/api/lang`, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ userId, lang, 方向: direction }), // 添加 userId
  });
  if (!response.ok) throw new Error(`请求失败 (${response.status})`);
  return await response.json();
};

/**
 * 标记用户为非新用户
 */
export const markUserNotNew = async (userId: string): Promise<void> => {
  const response = await fetch(`${API_BASE_URL}/api/user/mark_not_new`, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ userId }), // 添加 userId
  });
  if (!response.ok) throw new Error(`标记用户状态失败 (${response.status})`);
};

/**
 * 更新当前计划的用户等级
 */
export const updatePlanLevel = async (userId: string, level: number): Promise<void> => {
  const response = await fetch(`${API_BASE_URL}/api/plan/level`, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ userId, level }), // 添加 userId
  });

  if (!response.ok) {
    const errorData = await response.json().catch(() => ({}));
    throw new Error(`更新计划等级失败: ${errorData.error || response.statusText}`);
  }
};

export const try_login = async (username: string, password: string): Promise<{
  success: boolean;
  message: string;
  userId: string;
}> => {
  const response = await fetch(`${API_BASE_URL}/api/login/login`, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ userId: username, password: password }),
  });
  if (!response.ok) {
    let errorData = { message: response.statusText };
    try {
      errorData = await response.json();
    } catch (e) {}
    throw new Error(`登录失败: ${errorData.message || response.statusText}`);
  }
  return await response.json();
}
 export const  try_register = async (username: string, password: string) => {
  const response = await fetch(`${API_BASE_URL}/api/login/register`, {

    method: "POST",
    headers: { "Content-Type": "application/json" },
    // 添加 body，发送 userId 和 password
    body: JSON.stringify({ userId: username, password: password }),
  })

  if (!response.ok) {
    // 尝试解析后端返回的错误信息
    let errorData = { message: response.statusText }; // 默认使用 statusText (注意后端注册失败返回的是 errormsg)
    try {
      errorData = await response.json();
    } catch (e) {
       // 如果解析 JSON 失败，则忽略
    }
    throw new Error(`注册失败: ${errorData.message || response.statusText}`);
  }
  return await response.json();
 }

 
 // 定义项目接口 (根据 project.py get_project_list 返回的数据结构调整)
 export interface Project { // 添加 export 关键字
   id: string; // 假设项目有 ID
   name: string; // 假设项目有名称
   // 可以根据实际返回的数据添加更多字段
 }
// 定义项目数据接口
export interface ProjectData {
  name: string;
  code: string;
  md: string;
  answer: string;
}
 
 /**
  * 获取用户的项目列表
  */
 export const getProjectList = async (userId: string, lang: string, direction: string, step: number): Promise<Project[]> => {
   const params = new URLSearchParams({
     userId: userId,
     lang: lang,
     direction: direction,
     step: step.toString(), // 将 step 转换为字符串
   });
   const response = await fetch(`${API_BASE_URL}/api/project/list?${params.toString()}`);
   if (!response.ok) {
     let errorData = { message: `获取项目列表失败 (${response.status})` };
     try {
       const data = await response.json();
       errorData.message = data.error || errorData.message;
     } catch (e) {}
     throw new Error(errorData.message);
   }
   return await response.json();
 };

/**
 * 创建新项目
 */
// 更新 newProject 返回值类型为 ProjectData
export const newProject = async (
  userId: string,
  lang: string,
  direction: string,
  step: number,
  proj_name: string // 注意：proj_name 仍然需要传递给后端，后端会用它覆盖生成的名字
): Promise<ProjectData> => { // 返回完整的 ProjectData
  const response = await fetch(`${API_BASE_URL}/api/project/new`, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    // 在请求体中也发送 proj_name
    body: JSON.stringify({ userId, lang, direction, level: step, proj_name: proj_name }),
  });
  if (!response.ok) {
    let errorData = { message: `创建新项目失败 (${response.status})` };
    try {
      const data = await response.json();
      errorData.message = data.error || errorData.message;
    } catch (e) {}
    throw new Error(errorData.message);
  }
  return await response.json();
};


export const save_new_Project = async (
  userId: string,
  lang: string,
  direction: string,
  step: number,
  projectData: ProjectData // 接收 ProjectData 对象
): Promise<void> => {
  const response = await fetch(`${API_BASE_URL}/api/project/save_new`, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    // 发送包含 projectData 键的对象
    body: JSON.stringify({ userId, lang, direction, step, projectData: projectData }),
  });
  if (!response.ok) {
    let errorData = { message: `保存项目失败 (${response.status})` };
    try {
      const data = await response.json();
      errorData.message = data.error || errorData.message;
    } catch (e) {}
    throw new Error(errorData.message);
  }
};

/**
 * 保存现有项目
 */
export const save_project = async (
  userId: string,
  lang: string,
  direction: string,
  step: number,
  projectIndex: number, // 添加 projectIndex 参数
  projectData: ProjectData // 接收 ProjectData 对象
): Promise<void> => {
  const response = await fetch(`${API_BASE_URL}/api/project/save`, { // 调用 /api/project/save
    method: "POST",
    headers: { "Content-Type": "application/json" },
    // 发送包含 projectData 和 projectIndex 的对象
    body: JSON.stringify({ userId, lang, direction, step, projectIndex, projectData: projectData }),
  });
  if (!response.ok) {
    let errorData = { message: `保存项目失败 (${response.status})` };
    try {
      const data = await response.json();
      errorData.message = data.error || errorData.message;
    } catch (e) {}
    throw new Error(errorData.message);
  }
};


/**
 * 获取项目内容
 */
export const getProject = async (
  userId: string,
  lang: string,
  direction: string,
  step: number,
  projectIndex: number
): Promise<ProjectData> => {
  const params = new URLSearchParams({
    userId: userId,
    lang: lang,
    direction: direction,
    step: step.toString(),
    projectIndex: projectIndex.toString(),
  });
  const response = await fetch(`${API_BASE_URL}/api/project/get?${params.toString()}`);
  if (!response.ok) {
    let errorData = { message: `获取项目内容失败 (${response.status})` };
    try {
      const data = await response.json();
      errorData.message = data.error || errorData.message;
    } catch (e) {}
    throw new Error(errorData.message);
  }
  return await response.json();
};


// 定义执行结果接口
export interface ExecResult {
  success?: boolean; // 是否成功执行 (可能不存在，例如仅测试)
  all_passed?: boolean; // 测试是否全部通过
  message?: string; // 错误或成功消息
  output?: string; // 代码的标准输出
  test_results?: any; // 测试用例结果 (具体类型待定，先用 any)
  // 可能还有其他字段，根据后端实际返回调整
}

// 定义评估结果接口
export interface EvaluateResult {
  evaluation: string; // AI 评估文本
}

/**
 * 执行用户代码
 */
export const executeCode = async (
  userId: string,
  lang: string,
  direction: string,
  step: number,
  projectIndex: number,
  userCode: string
): Promise<ExecResult> => {
  const response = await fetch(`${API_BASE_URL}/api/exec`, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ userId, lang, direction, step, projectIndex, userCode }),
  });
  if (!response.ok) {
    let errorData = { message: `执行代码失败 (${response.status})` };
    try {
      const data = await response.json();
      errorData.message = data.error || errorData.message;
    } catch (e) {}
    throw new Error(errorData.message);
  }
  return await response.json();
};

/**
 * 评估用户代码
 */
export const evaluateCode = async (
  userId: string,
  lang: string,
  direction: string,
  step: number,
  projectIndex: number,
  testResults: any, // 接收执行结果中的 test_results
  userCode: string
): Promise<EvaluateResult> => {
  const response = await fetch(`${API_BASE_URL}/api/evaluate`, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ userId, lang, direction, step, projectIndex, testResults, userCode }),
  });
  if (!response.ok) {
    let errorData = { message: `评估代码失败 (${response.status})` };
    try {
      const data = await response.json();
      errorData.message = data.error || errorData.message;
    } catch (e) {}
    throw new Error(errorData.message);
  }
  return await response.json();
};
